package emas.server.core;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import emas.shared.Location;
import emas.shared.SQLConstants;
import emas.shared.SensorData;

public class TemperaturDataManager {
	private static TemperaturDataManager instance = new TemperaturDataManager();


	private ArrayList<Location> locations;

	private TemperaturDataManager() {
	}

	public void updateData() {
		System.out.println("Updating Data...");
		MySQLConnectionManager manager = MySQLConnectionManager.getInstance();
		locations = LocationManager.getInstance().getLocations();
		ArrayList<SensorData> data;
		ResultSet set = null;
		for (Location location : locations) {
			try {
				data = new ArrayList<SensorData>();
				String query = "SELECT * FROM "
						+ SQLConstants.temperatur_table + " WHERE "
						+ SQLConstants.location_id + "=" + location.getId()
						+ " ORDER BY " + SQLConstants.temperatur_record_id
						+ " DESC LIMIT 0," + SQLConstants.maxRecordedDataNr;
				System.out.println("SQL Query:" +query);
				set = manager.selectQuery(query);
				while (set.next()) {
					SensorData tempData = new SensorData(
							set.getInt(SQLConstants.temperatur_record_id), 
							set.getInt(SQLConstants.location_id),
							set.getString(SQLConstants.temperatur_sensor),
							set.getFloat(SQLConstants.temperatur_avgtemp),
							set.getDate(SQLConstants.temperatur_date), 
							set.getTime(SQLConstants.temperatur_time));
					data.add(tempData);
					
				}
				location.setLast250DataEntry(data);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static TemperaturDataManager getInstance() {
		if (instance == null) {
			instance = new TemperaturDataManager();
		}
		return instance;
	}
}
